package com.sn.shop.utils;

import com.alibaba.fastjson.JSON;
import com.sn.shop.dao.RedisDao;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @auther sn
 * @date 2018/1/23
 * @description TODO
 */
public class JwtUtil {

    public static final long EXPIRATION_TIME = 3600_000_000L; // 1000 hour
    public static final String SECRET = "ThisIsASecret";
    public static final String TOKEN_PREFIX = "";
    public static final String TOKEN = "token";

    /**
     * 生产token
     * @param username
     * @return
     */
    public static String generateToken(String username) {
        HashMap<String, Object> map = new HashMap<>();
        //you can put any data in the map
        map.put("username", username);
        String jwt = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        return jwt;
    }

    /**
     * 通过token获取用户信息
     * @param userJson
     * @return
     */
    public static UserDetails getUserDetailsByJson(String userJson) {
        return JSON.parseObject(userJson, UserDetails.class);
    }

    /**
     * 验证token是否正确
     * @param token
     * @return
     */
    public static String validateToken(String token) {
        if (token != null) {
            // parse the token.
            Map<String,Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            String username = (String) (body.get("username"));
            if(username == null || username.isEmpty())
                throw new TokenValidationException("Wrong token without username");
            else {
                return username;
            }
        }else{
            throw new TokenValidationException("Missing token");
        }
    }

    static class TokenValidationException extends RuntimeException {
        public TokenValidationException(String msg) {
            super(msg);
        }
    }
}
